#include "msgsocket.h"
#include "threadpool.h"
#include "string.h"

MsgSocket::MsgSocket(TcpSocket *socket)
{
    m_socket = socket;
    m_socket->createRecvCallback(std::bind(&MsgSocket::recvMsg, this, std::placeholders::_1));
}

void MsgSocket::recvMsg(char *msg)
{
    printf("MsgSocket::RecvMsg: %s\n", msg);
    m_msgQueue.push(msg);
    if(m_socket->m_tdPool != nullptr)
    {
        Task *task = new Task;
//        task->arg = msg;
        task->function = std::bind(&MsgSocket::procMsg, this);
        m_socket->m_tdPool->addTask(task);
    }else
    {
        procMsg();
    }
}

void MsgSocket::procMsg(void)
{
    std::string msg = m_msgQueue.front();
    m_msgQueue.pop();
    printf("MsgSocket::procMsg: %s\n", msg.c_str());
    for(int i = 0; i < msg.length(); i++)
    {
        if((msg[i] > ('a'-1)) && (msg[i] < ('z'+1)))
        {
            msg[i] -= 32;
        }
    }
    m_socket->sendData(msg.c_str());
}
